/*
 * Thread.h
 *
 *	Author: stravant
 *	Description:
 *		
 */

#ifndef THREAD_H_
#define THREAD_H_

#include <boost/thread/thread.hpp>

#include "../core/EventLoop.h"

namespace tbt {

class Thread: public RefCounted<Thread> {
public:
	Thread() {
		std::cout << "Thread::Thread()\n";
	}
	virtual ~Thread() {}

	void setEventLoop(Ref<EventLoop> evt) {mEventLoop = evt; }
	Ref<EventLoop> getEventLoop() const {return mEventLoop; }

	void launch() {
		if (mLaunched)
			unreachable;
		mThread = boost::thread(boost::bind(&Thread::runTrampoline, this));
	}
protected:
	virtual void run() = 0;

private:
	void runTrampoline() {
		std::cout << "Thread::runJump()\n";
		run();
	}
	Ref<EventLoop> mEventLoop;
	boost::thread mThread;
	bool mLaunched;
};

class WorkerThread: public Thread {
public:
	WorkerThread() {
		std::cout << "WorkerThread::WorkerThread()\n";
		setEventLoop(new EventLoop());
	}
	~WorkerThread() {}

private:
	void run() {
		std::cout << "Starting worker thread " << this << "\n";
		getEventLoop()->run();
	}
};

//Make a worker thread and wait for it to start
Ref<WorkerThread> StartWorkerThread();

}

#endif /* THREAD_H_ */
